package com.zhiche.lisa.lspm.service.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.lspm.dao.model.carrier.bo.VehicleQueueBO;
import com.zhiche.lisa.lspm.dao.model.weiXin.WeiXinExport;
import com.zhiche.lisa.lspm.vo.common.RestVO;
import com.zhiche.lisa.lspm.vo.common.ShipOrderVO;
import com.zhiche.lisa.lspm.vo.driver.ErpShipToByLicenseVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ErpUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ErpUtil.class);

    @Value("${erp.url}")
    private String erpUrl;

    @Value("${erp.vehicleQueueURL}")
    private String vehicleQueueURL;

    @Value("${erp.socketTimeout}")
    private Integer socketTimeout;

    @Value("${erp.addTrajectoryURL}")
    private String addTrajectoryURL;

    @Value("${erp.cancelQueueURL}")
    private String cancelQueueURL;

    @Value("${erp.getWeChatPublicNumberUsageRateURL}")
    private String getWeChatPublicNumberUsageRateURL;

    @Value("${erp.vehicleReportingUrl}")
    private String vehicleReportingUrl;


    /**
     * 推送报班到ERP
     */
    public void pushCheckin(VehicleQueueBO vehicleQueueBO) throws BaseException {
        // 发送报班请求给erp
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        String strReturn = null;
        //fix me 推送erp报班源司机名--->lspm
//        vehicleQueueBO.setDriverName("lspm");
        Map<String,Object> map = new HashMap<>();
        map.put("truck",vehicleQueueBO.getLicense());
        map.put("gmt_queue",new Date());
        String jsonParam = JSON.toJSONString(map);
        try {
            LOGGER.info("报班-->连接推送ERP url:{},param:{}", vehicleReportingUrl, jsonParam);
            strReturn = HttpClientUtil.postJson(vehicleReportingUrl, headNamePairs, jsonParam, socketTimeout);
            LOGGER.info("报班-->连接推送ERP result:{}", strReturn);
        } catch (Exception e) {
            LOGGER.error("报班异常-->连接推送ERP连接异常", e.getMessage());
            //throw new BaseException("报班异常-->连接推送ERP连接异常");
        }
        if (StringUtils.isNotBlank(strReturn)) {
            RestVO restVO = JSON.parseObject(strReturn, new TypeReference<RestVO>() {
            });
            boolean result = restVO.getSuccess();
            String message = restVO.getMessage();
            if (!result) {
                LOGGER.error(message);
                //throw new BaseException("报班异常-->连接推送ERP" + message);
            }
        } else {
            LOGGER.error("报班异常-->连接推送ERP连接未响应结果->", strReturn);
            //throw new BaseException("报班异常-->连接推送ERP连接未响应结果");
        }

    }


    /**
     * 推送取消报班报班到ERP
     */
    public void pushCancelCheckin(Long driverQueueId) throws BaseException {
        // 发送报班请求给erp
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        VehicleQueueBO vehicleQueueBO = new VehicleQueueBO();
        vehicleQueueBO.setDriverQueueId(driverQueueId);
        LOGGER.info("取消报班推送erp url:{},param:{}", erpUrl + cancelQueueURL, JSON.toJSONString(vehicleQueueBO));
        String strReturn = HttpClientUtil.postJson(erpUrl + cancelQueueURL, headNamePairs, JSON.toJSONString(vehicleQueueBO), socketTimeout);
        LOGGER.info("取消报班推送erp result:{}", strReturn);
        if (StringUtils.isNotBlank(strReturn)) {
            return;
        }
        throw new BaseException("取消报班推送erp");
    }

    /**
     * 发送在途到ERP
     */
    public void pushLoaction(ErpShipToByLicenseVO erpShipToByLicenseVO) throws BaseException {
        // 发送在途请求给 erp
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        String strReturn = HttpClientUtil.postJson(erpUrl + addTrajectoryURL, headNamePairs, JSON.toJSONString(erpShipToByLicenseVO), socketTimeout);
        Boolean result = null;
        if (!org.springframework.util.StringUtils.isEmpty(strReturn)) {
            RestVO restVO = JSON.parseObject(strReturn, new TypeReference<RestVO<ShipOrderVO>>() {
            });
            result = restVO.getSuccess();
        }
        if (org.springframework.util.StringUtils.isEmpty(strReturn)
                || result == false) {
            LOGGER.error("请求erp位置上报异常");
            //throw new BaseException(-1, "位置上报异常，请稍后再试！");
        }
    }

    /**
     * 获取微信公众号使用率情况
     */
    public List<WeiXinExport> getWeChatPublicNumberUsageRate(String timeStamp) throws BaseException {
        String url = erpUrl + getWeChatPublicNumberUsageRateURL;
        HashMap<String, String> param = Maps.newHashMap();
        param.put("timeStamp", timeStamp);
        LOGGER.info("insertERPRate url:{},params:{}", url, JSONObject.toJSONString(param));
        String strReturn = HttpClientUtil.postJson(url, null, JSONObject.toJSONString(param), socketTimeout);
        LOGGER.info("insertERPRate result:{}", strReturn);
        if (StringUtils.isNotEmpty(strReturn)) {
            JSONObject jsonObject = JSONObject.parseObject(strReturn);
            String data = jsonObject.getString("data");
            if (!StringUtils.isEmpty(data)) {
                return JSONObject.parseArray(data, WeiXinExport.class);
            }
        }
        return null;
    }
}
